package com.jay.media.video.openglesdemo

import android.app.ActivityManager
import android.content.Context
import android.opengl.GLES20.GL_COLOR_BUFFER_BIT
import android.opengl.GLSurfaceView
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

class MainActivity : AppCompatActivity() {

    companion object {
        const val TAG = "GL"
    }

    private lateinit var glSurfaceView: GLSurfaceView
    private var renderSet = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        glSurfaceView = GLSurfaceView(this)
        setContentView(glSurfaceView)

        checkVersion()
    }

    private fun checkVersion() {
        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        var deviceConfig = activityManager.deviceConfigurationInfo

        Log.d(TAG, "device config ：${deviceConfig.reqGlEsVersion}")
        var supportsEs2 = deviceConfig.reqGlEsVersion >= 0x20000
        if (supportsEs2) {
            glSurfaceView.setEGLContextClientVersion(2)
            glSurfaceView.setRenderer(TriangleRender())
            renderSet = true
        }
    }

    override fun onPause() {
        super.onPause()
        if (renderSet) {
            glSurfaceView.onPause()
        }
    }

    override fun onResume() {
        super.onResume()
        if (renderSet) {
            glSurfaceView.onResume()
        }
    }

    inner class TriangleRender : GLSurfaceView.Renderer {
        override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
            gl?.glClearColor(1.0f, 0.0f, 0.0f, 0.0f)
        }

        override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
            gl?.glViewport(0, 0, width, height)
        }

        override fun onDrawFrame(gl: GL10?) {
            gl?.glClear(GL_COLOR_BUFFER_BIT)
        }
    }
}